import { AnyAction, Reducer } from 'redux';
import { EffectsCommandMap } from 'dva';
import { message } from 'antd';
import { fetchValidation } from '@/utils';
import {
  queryTypeList,
  queryProblemList,
  queryProcessStatus,
  addRecord,
} from './service';


export type Effect = (
  action: AnyAction,
  effects: EffectsCommandMap & { select: <T>(func: (state: {}) => T) => T },
) => void;

export interface ModelType {
  namespace: string;
  state: {};
  effects: {
    fetch: Effect;
    typeList: Effect;
    processStatus: Effect;
    addRecord: Effect;
  };
  reducers: {
    save: Reducer;
  };
}

const Model: ModelType = {
  namespace: 'logisCenterProblemList',

  state: {
    data: {},
    typeList: [],
    processStatus: {},
  },

  effects: {
    * fetch({ payload }, { call, put }) {
      const response = yield call(queryProblemList, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: { type: 'data', value: data.body },
      });
    },
    * addRecord({ payload }, { call, put }) {
      const response = yield call(addRecord, payload.params);
      const data = fetchValidation(response);
      if (data) {
        message.success(data.msg);
        yield put({
          type: 'fetch',
          payload: payload.query,
        });
      }
    },
    * typeList({ payload }, { call, put }) {
      const response = yield call(queryTypeList);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: { type: 'typeList', value: data.body },
      });
    },
    * processStatus({ payload }, { call, put }) {
      const response = yield call(queryProcessStatus, payload);
      const data = fetchValidation(response);
      yield data && put({
        type: 'save',
        payload: { type: 'processStatus', value: data.body },
      });
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        [payload.type]: payload.value,
      };
    },
  },
};

export default Model;
